﻿/*
 * https://leetcode.cn/problems/degree-of-an-array/
 */

using System.Collections.Generic;
using System.Linq;

namespace DegreeOfAnArray
{
    public class Solution
    {
        public int FindShortestSubArray(int[] nums)
        {
            var counts = new Dictionary<int, int>();
            foreach (var n in nums)
            {
                if (counts.TryGetValue(n, out int value))
                {
                    counts[n] = ++value;
                }
                else
                {
                    counts[n] = 1;
                }
            }

            var maxCount = counts.Values.Max();

            var result = int.MaxValue;
            foreach (var item in counts)
            {
                if (item.Value != maxCount) 
                {
                    continue;
                }

                var start = nums.ToList().IndexOf(item.Key);
                var end = nums.ToList().LastIndexOf(item.Key);

                if (end - start < result)
                {
                    result = end - start;
                }
            }

            return result + 1;
        }
    }
}
